<template>
  <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px">
    <div class="form">
      <div style="display: flex;">
        <el-form-item label="品牌名称">
          <el-input v-model="state.dataForm.brandName" size="small" type="text" clearable
            placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌类型">
          <el-select v-model="state.dataForm.brandType" placeholder="请选择品牌类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="自有品牌" value="1"></el-option>
            <el-option label="代理品牌" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产地">
          <el-select v-model="state.dataForm.brandClassId" placeholder="请选择产地" clearable>
            <el-option v-for="option in brandClassifyOptions" :key="option.id" :label="option.className"
                       :value="option.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="state.dataForm.status" placeholder="请选择审核状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="已通过" value="1"></el-option>
            <el-option label="已驳回" value="2"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item>
          <el-button @click="queryData" style="background: rgba(22, 119, 255, 1); color: #fff; border-radius: 5px;font-size: 15px;">{{
            $t("query") }}</el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm"
            style="background: rgba(239, 244, 255, 1); border: 1px solid rgba(16, 98, 202, 1); color: #1062ca; border-radius: 5px;font-size: 15px;">重置</el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="listSave"  v-if="state.hasPermission('noc:lilililililili:save')"
                     style="background: rgba(239, 244, 255, 1); border: 1px solid rgba(16, 98, 202, 1); color: #1062ca; border-radius: 5px">批量插入</el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleAdd()" style="background: #1677ff; color: #fff;font-size: 15px;">绑定品牌</el-button>
        </el-form-item>
      </div>
    </div>

    <el-table v-if="state.total > 0"
      :header-cell-style="{ background: '#eef1f6', color: '#1f2d3d', 'border-color': '#dfe6ec' }"
      v-loading="state.dataListLoading" :data="state.dataList" border
      @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
      <!-- <el-table-column align="center" prop="certifiedId" label="认证编号" width="180"
        show-overflow-tooltip></el-table-column> -->
      <!-- <el-table-column align="center" prop="companyName" label="公司名称" width="180"
        show-overflow-tooltip></el-table-column> -->
      <el-table-column align="center" prop="brandName" label="品牌名称" width="240" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" label="品牌类型" width="240" show-overflow-tooltip>
        <template v-slot="scope">
          <span v-if="scope.row.brandType === '1'">自有品牌</span>
          <span v-else-if="scope.row.brandType === '2'">代理品牌</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="产地" width="240" show-overflow-tooltip prop="brandClassName"></el-table-column>
      <el-table-column align="center" prop="saleRegion" label="区域" width="240"
        show-overflow-tooltip></el-table-column>
      <!-- <el-table-column align="center" prop="createAt" label="认证申请时间" width="180"
        show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="auditor" label="审核人" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="auditTime" label="审核时间" width="180" show-overflow-tooltip></el-table-column> -->
      <el-table-column align="center" label="审核状态" width="240" show-overflow-tooltip>
        <template v-slot="scope">
          <span v-if="scope.row.status === '0'" style="color: #f56c6c">待审核</span>
          <span v-else-if="scope.row.status === '1'" style="color: #67c23a">已通过</span>
          <span v-else-if="scope.row.status === '2'" style="color: #f56c6c">已驳回</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="未通过原因" width="240" show-overflow-tooltip>
        <template v-slot="scope">
          <span v-if="scope.row.status !== '1'">{{ scope.row.rejectReason || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" prop="readOnly" label="操作" width="180">
        <template v-slot="scope">
          <!-- 列表按钮 -->
          <el-button link @click="handleEdit(scope.row)"
                     style="color: rgba(22, 119, 255, 1);">更新</el-button>
          <el-button link @click="detachEvent(scope.row)" v-if="scope.row.status === '1'"
                     style="color: rgba(22, 119, 255, 1);">取消绑定</el-button>



        </template>
      </el-table-column>
    </el-table>
    <div v-else style="display: flex;justify-content: center;align-items: center;">
      <img style="width: 467px;height: 368px; margin-top: 100px;" src="@/assets/images/empty.png" alt="">
    </div>
  </el-form>
  <el-pagination v-if="state.total > 0" :current-page="state.page" :page-sizes="[10, 20, 50, 100]"
    :page-size="state.limit" :total="state.total" layout="total, sizes, prev, pager, next, jumper"
    @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>
  <BrandViewDialog ref="viewDialogRef" @success="state.getDataList()" />
  <!-- 弹窗 -->
  <BrandAddDialog ref="addDialogRef" @success="state.getDataList()" />
  <!-- 企业认证弹窗 -->
  <CompanyAuthDialog />
</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import useView from "@/hooks/useView";
import { nextTick, reactive, ref, toRefs, onMounted } from "vue";
import router from "@/router";
import BrandViewDialog from "@/components/BrandViewDialog.vue";
import BrandAddDialog from "@/components/BrandAddDialog.vue";
import CompanyAuthDialog from "@/components/CompanyAuthDialog.vue";



const addDialogRef = ref<InstanceType<typeof BrandAddDialog>>();



const view = reactive({
  getDataListURL: "/noc/authbrandaudit/list",
  getDataListIsPage: true,
  dataForm: {
    status: "",
    companyName: "",
    brandName: "",
    brandType: "",
    brandClassId: ""
  }
});
// 分类选项
const classOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);
// 状态多选值
const selectedStatus = ref([]);
// 绑定品牌
const handleAdd = () => {
  addDialogRef.value?.open();
};
// 产地选项
const brandClassifyOptions = ref<any[]>([]);
//获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "0":
      return "待审核";
    case "1":
      return "已通过";
    case "2":
      return "已驳回";
    default:
      return "";
  }
};

//获取状态样式
const getStatusClass = (status: string) => {
  switch (status) {
    case "0":
      return "el-tag--info";
    case "1":
      return "el-tag--success";
    case "2":
      return "el-tag--danger";
    default:
      return "";
  }
};

//处理搜索
const handleSearch = () => {
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

//处理分页
const handlePage = (page: number) => {
  state.page = page;
};

// 修改查询按钮的点击处理
const queryData = () => {
  saveCurrentQuery();
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 修改重置方法以清除保存的查询条件
const resetForm = () => {
  view.dataForm.companyName = "";
  view.dataForm.status = "";
  view.dataForm.brandName = "";
  view.dataForm.brandClassId = "";
  view.dataForm.brandType = "";
  // 重置状态多选值
  selectedStatus.value = [];
  // 重置级联选择器的值
  selectedClassPath.value = [];
  // 清除保存的查询条件
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

const listSave = () => {
  baseService.get('/noc/authbrandaudit/listsave').then(res => {
    res.data;

  });
};

// 在执行查询前保存当前查询条件
const saveCurrentQuery = () => {
  const query = {
    dataForm: { ...state.dataForm },
    selectedStatus: [...selectedStatus.value],
    selectedClassPath: [...selectedClassPath.value]
  };
  sessionStorage.setItem("nocproductListQuery", JSON.stringify(query));
};

// 获取分类列表
const getBrandClassifyList = () => {
  baseService.get('/base/basebrandclassify/queryList2').then(res => {
    // 确保数据结构符合级联选择器要求
    brandClassifyOptions.value = res.data;
    console.log('产地数据加载成功:', brandClassifyOptions.value);
  }).catch(error => {
    console.error('获取分类数据出错:', error);
    ElMessage.error('获取分类数据出错');
  });
};

// 在 onMounted 中添加
const route = useRoute();
onMounted(() => {
  // getClassList();
  state.getDataList();
});

const viewDialogRef = ref<InstanceType<typeof BrandViewDialog>>();
// 跳转查看页面
const handleView = (row: any) => viewDialogRef.value?.open(row, "view");
const handleEdit = (row: any) => {
  addDialogRef.value?.open(row); // 传入当前行数据
};
const detachEvent = async (row: any) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要取消绑定品牌 "${row.brandName}" 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 用户确认后执行取消绑定操作
    const id = row.id;
    baseService.post('/noc/authbrandaudit/detachEvent', id).then(res => {
      ElMessage.success('取消绑定成功');
      state.getDataList();
    });

  } catch (error) {
    // 用户点击取消或关闭对话框
    console.log('用户取消操作');
  }
};
const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;
// 加载分类和品牌数据
onMounted(() => {
  // getClassList();
  console.log("获取到的数据:", state.dataList);
  getBrandClassifyList();
});
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
}

.el-input {
  width: 218px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}



.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  /* 自动适应列宽，每列至少240px */
  gap: 16px;
  /* 元素间距 */
}

.form {
  display: flex;
  justify-content: space-between;
}
</style>
